package com.server.util;

import java.io.InputStream;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.constants.SystemVariables;
import com.crypto.AsymmetricCryptor;
import com.crypto.SymmetricCryptor;
import com.helpers.SystemProperties;


/**
 * @author friedlma
 */
public class ApplicationStartUpListener implements ServletContextListener {

    //private ServletContext context = null;
    
    public ApplicationStartUpListener() {
    }

    public void contextInitialized(ServletContextEvent event) {
       System.out.println("-------------- Starting the Website!!!!! --------------");
       
       
//       System.out.println("-------------- Try DB Connection!!!!! --------------");
//       try {
//    	   DBConnector dbc=DBConnector.getInstance();
//    	   dbc.getConnection();
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
       
       System.out.println("-------------- Reading Properties!!!!! --------------");
     
       SystemProperties sp=SystemProperties.getInstance();  //Instanz holen
       String path = event.getServletContext().getInitParameter("systempropertiesfile");  //Pfad der Property Datei lesen    
       final InputStream is = event.getServletContext().getResourceAsStream(path);	//Stream der Datei erzeugen
       sp.loadProperties(is); //Property laden
       
       
       System.out.println("-------------- Load Keys!!!!! --------------");
       String secKey=(String)sp.getProperties().get("secKey");
       String privKey=(String)sp.getProperties().get("privKey");
       String pubKey=(String)sp.getProperties().get("pubKey");
       
       SymmetricCryptor sc=new SymmetricCryptor(false);
       sc.setSecretKey(sc.readKey(secKey));
       
       AsymmetricCryptor ac=new AsymmetricCryptor(false);
       ac.setPrivateKey(ac.readPrivateKey(privKey));
       ac.setPublicKey(ac.readPublicKey(pubKey));
       
       SystemVariables.SECRET_KEY=sc.getSecretKey();
       SystemVariables.PRIVATE_KEY=ac.getPrivateKey();
       SystemVariables.PUBLIC_KEY=ac.getPublicKey();
       
       System.out.println("Secret Key: "+SystemVariables.SECRET_KEY);
       System.out.println("Private Key: "+ SystemVariables.PRIVATE_KEY);
       System.out.println("Public Key: "+SystemVariables.PUBLIC_KEY);
       
    }
    

    public void contextDestroyed(ServletContextEvent event) {
        //this.context = null;
    	System.out.println("-------------- Closing the Website!!!!! --------------");
    }
}
